﻿using System;
using System.Web;
using System.Linq;
using System.Web.Mvc;
using KPIS.GERP.MVC.Models;
using KPIS.GERP.MVC.Classes;
using KPIS.GERP.SERVICE.DAL;
using KPIS.GERP.SERVICE.Model;
using System.Collections.Generic;

namespace KPIS.GERP.MVC.Controllers
{
    public class SalaryPromoteController : Controller
    {
        SsMng ssMng = new SsMng();
        Employee employeeDal = new Employee();
        SalaryPromoteDal salaryPromoteDal = new SalaryPromoteDal();

        public ActionResult Index()
        {
            var sps = salaryPromoteDal.Select().OrderByDescending(o => o.sp_seq).ToList();
            return View(sps);
        }

        public ActionResult ViewDetails(int RefSeq)
        {
            var sp = salaryPromoteDal.Select(new salary_promote { sp_seq = RefSeq }).First();
            approval_task approvalTask = null;
            approval_task[] allApprovalTask = null;

            if (sp != null)
            {
                using (var service = new ApprovalServiceWcfIisRef.AbsenceApprovalWCFClient())
                {
                    allApprovalTask = service.GetTasks();
                }
            }

            if (allApprovalTask != null)
            {
                approvalTask = allApprovalTask.FirstOrDefault(o => o.Reference.ref_seq == sp.sp_seq && o.Reference.rule_approve_group_seq == 1001);
            }

            ViewBag.sp = sp; 

            return View(approvalTask);
        }

        public ActionResult Create()
        {
            var positions = employeeDal.GetHrmMpPositions(null, null, null, null, null, null, null, null, false, false, false, false, false, false);
            
            ViewBag.Positions = positions
                .Select(c => new SelectListItem
                {
                    Value = c.pos_seq.ToString(),
                    Text = c.pos_ref + " - " + c.pos_name
                });

            ViewBag.EmployeesActive = employeeDal.GetHrmPsEmployeeLite();

            return View();
        }

        [HttpPost]
        public ActionResult Create(salary_promote model, FormCollection formCollection)
        {
            string resultMessage = "ยังไม่ทำอะไร";
            try
            {
                model.created_by = ssMng.EmpSeqI;

                List<salary_promote_detail> datadetail = new List<salary_promote_detail>();
                var employees = employeeDal.GetHrmPsEmployeeLite();
                var common = new Classes.Common();
                foreach(var employee in employees)
                {
                    if(formCollection["emp_chb_salary_" + employee.emp_seq].StartsWith("true"))
                    {
                        datadetail.Add(new salary_promote_detail
                            {
                                emp_seq = employee.emp_seq,
                                old_salary = common.MakeZeroDecimal(formCollection["emp_old_salary_" + employee.emp_seq]),
                                new_salary = common.MakeZeroDecimal(formCollection["emp_txt_salary_" + employee.emp_seq]),
                                pos_seq = employee.pos_seq.Value,
                                sp_seq = model.sp_seq
                            });
                    }
                }
                model.Details = datadetail;
                foreach (var key in formCollection.AllKeys)
                {

                    resultMessage += key + " = " + formCollection[key] + "\r\n";
                    // etc.
                }
                resultMessage += "----\r\n";
                foreach (var key in formCollection.Keys)
                {
                    resultMessage += key + " = " + formCollection[key.ToString()] + "\r\n";
                    // etc.
                } 
                salaryPromoteDal.Insert(model);
                ViewBag.Message = resultMessage;
                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public ActionResult Edit(int sp_seq)
        {
            var sp = salaryPromoteDal.Select(new salary_promote { sp_seq = sp_seq }).First();
            return View(sp);
        }

        [HttpPost]
        public ActionResult Edit(salary_promote model)
        {
            try
            {
                salaryPromoteDal.Update(model);
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        public ActionResult Delete(int sp_seq)
        {
            var sp = salaryPromoteDal.Select(new salary_promote { sp_seq = sp_seq }).First();
            return View(sp);
        }

        [HttpPost]
        public ActionResult Delete(int sp_seq, FormCollection collection)
        {
            try
            {
                salaryPromoteDal.Delete(sp_seq, ssMng.EmpSeqI);
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        public ActionResult Confirm(int? emp_seq, int RefSeq, int RefTypeSeq, string status, string requestTitle)
        {
            if (String.IsNullOrWhiteSpace(emp_seq.ToString()) || String.IsNullOrWhiteSpace(RefSeq.ToString())
                || String.IsNullOrWhiteSpace(status))
            {
                ViewBag.Message = "รูปแบบข้อมูลไม่ถูกต้อง";
                return RedirectToAction("Create", "SalaryPromote");
            }
            else
            {
                SendApproval app = new SendApproval();
                app.Title = requestTitle;
                app.AbsenceSeq = RefSeq;
                app.EmpSeq = (int)emp_seq;
                app.Status = status;

                try
                {
                    using (var serviceClient = new ApprovalServiceIisRef.ServiceClient())
                    {
                        string outMessage;
                        serviceClient.CreateAbsenceTask(app.Title, app.EmpSeq, app.AbsenceSeq,
                            app.Status, RefTypeSeq, "A", ssMng.EmpSeqI, out outMessage);
                        ViewBag.Message = outMessage;
                    }
                }
                catch (HttpException ex)
                {
                    return HttpNotFound("อินเตอร์เน็ตไม่สามารถใช้งานได้");
                }
                catch (Exception ex)
                {
                    return HttpNotFound("ไม่สามารถใช้งานได้เนื่องจาก:" + ex.Message);
                }
            }
            //if (status == KPIS.GERP.SERVICE.WorkflowService.Class.Common.ProcessStatus)
            //    return RedirectToAction("Index", "ApprovalTask");
            //else
            return RedirectToAction("ViewDetails", "SalaryPromote", new { RefSeq });
        }
    }
}
